package li.com.springaidemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import li.com.springaidemo.exception.CustomException;
import li.com.springaidemo.mapper.UserMapper;
import li.com.springaidemo.pojo.User;
import li.com.springaidemo.server.WebSocketServer;
import li.com.springaidemo.service.UserService;
import li.com.springaidemo.utils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private WebSocketServer webSocketServer;
    @Override
    public User login(User user) {
        if (user.getUsername() == null || "".equals(user.getUsername())) {
            throw new CustomException("用户名不能为空");
        }
        if (user.getPassword() == null || "".equals(user.getPassword())) {
            throw new CustomException("密码不能为空");
        }
        // 2. 从数据库里面根据这个用户名和密码去查询对应的管理员信息，
        User user1=this.baseMapper.selectOne(new QueryWrapper<User>().eq("username",user.getUsername()).eq("password",user.getPassword()));
        if (user1 == null) {
            // 如果查出来没有，那说明输入的用户名或者密码有误，提示用户，不允许登录
            throw new CustomException("用户名或密码输入错误");
        }
        if(user1.getState()==0){
            throw new CustomException("用户已被禁用");
        }
        // 如果查出来了有，那说明确实有这个管理员，而且输入的用户名和密码都对；
//        保存token
        String token = JwtTokenUtils.getToken(user1.getId().toString(), user1.getPassword());
        user1.setToken(token);
        return user1;
    }

    @Override
    public void register(User user) {
        User user1 = this.baseMapper.selectOne(new QueryWrapper<User>().eq("name", user.getUsername()));
        if(user1!=null){
            throw new CustomException("用户名已存在");
        }
        user.setName("新用户");
        user.setState(1);
        user.setImg("https://ai-chunshuyingliang.oss-cn-beijing.aliyuncs.com/info.jpg");
        user.setPermissions(false);
        this.baseMapper.insert(user);
    }

    @Override
    public void logout(User user) {
        webSocketServer.onClose(user.getId().toString());
    }
}
